package com.sfx.算法专题.滑动窗口.固定窗口;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-08-08
 * Time: 14:16
 */
public class Code_7_findSubstring {

    static class Solution {
        public List<Integer> findSubstring(String s, String[] words) {
            Map<String,Integer> hash1 = new HashMap<>();
            List<Integer> res = new ArrayList<>();
            for(String x : words) {
                hash1.put(x,hash1.getOrDefault(x,0)+1);
            }
            int len = words[0].length();
            int m = words.length;
            for(int i =0;i<len;++i) {
                int left = i;
                int right = i;
                int cnt = 0;
                Map<String,Integer> hash2 = new HashMap<>();
                while(right + len <= s.length()) {
                    //进窗口前更新cnt
                    String in = s.substring(right,right+len);
                    if(hash2.getOrDefault(in,0) < hash1.getOrDefault(in,0)) {
                        cnt ++;
                    }
                    //进窗口
                    hash2.put(in,hash2.getOrDefault(in,0)+1);
                    if(right - left + 1 > m * len) {
                        //出窗口
                        String out = s.substring(left,left+len);
                        hash2.put(out,hash2.getOrDefault(out,0)-1);
                        //出窗口后更新cnt
                        if(hash2.getOrDefault(out,0) < hash1.getOrDefault(out,0)) {
                            cnt --;
                        }
                        left += len;
                    }
                    //更新结果
                    if(cnt == m) {
                        res.add(left);
                    }
                    right += len;
                }
            }
            return res;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        String[] words = {"foo", "bar"};
        solution.findSubstring("barfoothefoobarman", words);
    }
}